package pfq.demo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * TODO: document your custom view class.
 */
public class AView extends View {

    public AView(Context context) {
        super(context);
        init(null, 0);
    }

    public AView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public AView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    private void init(AttributeSet attrs, int defStyle) {

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.d("ViewRefresh", "AView-onMeasure()");
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        Log.d("ViewRefresh", "AView-onLayout()");
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.d("ViewRefresh", "AView-onDraw()");
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        Log.d("pangfq", "AView event.getX(): " + event.getX() + ", event.getY(): " + event.getY());
        Log.d("pangfq", "AView event.getRawX(): " + event.getRawX() + ", event.getRawY(): " + event.getRawY());
        Log.d("pangfq", "AView getLeft: " + getLeft() + ", getTop(): " + getTop());
        Log.d("pangfq", "AView getTranslationX: " + getTranslationX() + ", getTranslationY(): " + getTranslationY());

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // 如果down事件不消费的话，则其他事件也不会传递进来
            return true;

        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            // 如果是滑动事件，则实时更新自身位置
            // 获取父控件左上角距离屏幕顶部的距离
            int[] location = new int[2];
            ((View) getParent()).getLocationOnScreen(location);
            float y = event.getRawY() - ((float) location[1]);
            setY(y);
            return true;
        }

        return super.onTouchEvent(event);
    }
}
